<template>
  <div class="parking-content">
    <div class="camera-selection">
      <a-dropdown @command="handleSelect">
        <template #default>
          <a-button>
            {{
              selectedCamera
                ? selectedCamera
                : $t("ui.parkingManagement.selectParkingLot")
            }}
          </a-button>
        </template>
        <template #overlay>
          <a-menu>
            <a-menu-item key="default" disabled>{{
              $t("ui.parkingManagement.pleaseSelectParkingLot")
            }}</a-menu-item>
            <a-menu-item
              v-for="(camera, index) in cameras"
              style="background-color: var(--bg-color)"
              :key="index"
              @click="handleSelect(camera.name)"
            >
              {{ camera.name }}
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
      <a-button type="primary" @click="forceRefresh">{{
        $t("ui.parkingManagement.refreshImmediately")
      }}</a-button>
      <a-switch v-model:checked="isAutoRefreshEnabled" />
      <span>{{ $t("ui.parkingManagement.autoRefresh", { interval: 2 }) }}</span>
    </div>
    <a-table
      class="custom-table"
      :dataSource="parkingData"
      :pagination="paginationConfig"
      rowKey="id"
    >
      <a-table-column
        :title="$t('ui.parkingManagement.parkingLot')"
        dataIndex="parking"
        key="parking"
      />
      <a-table-column
        :title="$t('ui.parkingManagement.cameraId')"
        dataIndex="camera_id"
        key="camera_id"
      />
      <a-table-column
        :title="$t('ui.parkingManagement.occurrenceTime')"
        dataIndex="occurrence_time"
        key="occurrence_time"
      />
      <a-table-column
        :title="$t('ui.parkingManagement.licensePlate')"
        dataIndex="license_plate"
        key="license_plate"
      />
      <a-table-column
        :title="$t('ui.parkingManagement.color')"
        dataIndex="color"
        key="color"
      />
      <a-table-column :title="$t('ui.parkingManagement.image')" key="img_path">
        <template #default="{ record }">
          <img
            v-if="record.img_path"
            :src="getImageUrl(record.img_path)"
            :alt="
              record.license_plate || $t('ui.parkingManagement.noLicensePlate')
            "
            class="image small-image"
            @click="showModal(record.img_path)"
          />
        </template>
      </a-table-column>
    </a-table>
    <a-modal
      v-model:open="isModalVisible"
      :title="$t('ui.parkingManagement.imagePreview')"
      @cancel="handleCancel"
      footer=""
      :width="'90%'"
      :style="{
        position: 'absolute',
        top: '3%',
        left: '5%',
        maxHeight: '92vh',
        height: '92vh',
        overflowY: 'auto',
      }"
    >
      <div class="modal-image-container">
        <img :src="getImageUrl(currentImageSrc)" class="modal-image" />
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  onMounted,
  watch,
  onBeforeUnmount,
  computed,
} from "vue";
import { useI18n } from "vue-i18n"; // 引入 useI18n
import axios from "axios";
import { Dropdown, Button, Table, Modal, Switch, Menu } from "ant-design-vue";
import { formatDate } from "../utils"; // 根据您的项目结构调整路径
import { CameraEvent, CameraEventResponse } from "@/types/types"; // 导入 ApifoxModel 类型
interface Camera {
  name: string;
  address: string;
}

export default defineComponent({
  name: "ParkingManagement",
  components: {
    "a-dropdown": Dropdown,
    "a-button": Button,
    "a-table": Table,
    "a-table-column": Table.Column,
    "a-modal": Modal,
    "a-switch": Switch,
    "a-menu": Menu,
    "a-menu-item": Menu.Item,
    // "a-pagination": Pagination,
  },
  props: {
    msg: String,
  },
  setup() {
    const { t } = useI18n(); // 获取翻译函数
    // 摄像头地址和名称
    const cameras = ref<Camera[]>([
      { name: "王庄", address: "http://camera-a-address.com" },
      { name: "鳌峰大桥", address: "http://camera-b-address.com" },
      // { name: "光明港", address: "http://camera-c-address.com" },
    ]);
    const getImageUrl = (imagePath: string) => {
      const baseUrl =
        "https://36.248.25.143:31216/api/aisp-storage-center/v1/files?path=";
      const encodedPath = encodeURIComponent(imagePath);
      // console.log(
      //   `imagePath = ${imagePath}, 图片地址: ${baseUrl + encodedPath}`
      // );
      return baseUrl + encodedPath; // 构建完整的图片 URL
    };

    // 选中的摄像头
    const selectedCamera = ref<string | null>(null);
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页显示的条目数
    const total = ref(0); // 数据总条目数

    // 分页配置
    const paginationConfig = computed(() => ({
      current: currentPage.value,
      pageSize: pageSize.value,
      total: total.value,
      onChange: (page: number, size: number) => {
        currentPage.value = page; // 更新当前页码
        pageSize.value = size; // 更新每页显示条目数
        fetchParkingData(selectedCamera.value as string); // 重新获取数据
      },
    }));
    // 选择摄像头的处理函数
    const handleSelect = async (name: string) => {
      if (selectedCamera.value !== name) {
        currentPage.value = 1;
      }
      selectedCamera.value = name;
      // 可以在这里根据选择的地址获取停车数据
      console.log(`Selected camera: ${name}`);
      // 根据选择的地址获取停车数据
      await fetchParkingData(selectedCamera.value); // 调用获取停车数据的方法
    };

    const initialParkingData: CameraEventResponse = {
      data: [], // 初始化为一个空数组
      total: 0, // 初始化为 0
    };

    // 定义状态
    const parkingData = ref<CameraEvent[]>([]);
    const isModalVisible = ref(false);
    const currentImageSrc = ref("");
    // 获取数据的方法
    const fetchParkingData = async (address: string) => {
      try {
        // const response = await axios.get("/mock/parkingList");
        // parkingData.value = response.data.data.data;
        // total.value = response.data.data.total; // 更新总条目数
        // 请求数据的 URL
        const response = await axios.get("http://172.30.45.98:8080/events?", {
          params: {
            parking: address,
            page: currentPage.value, // 当前页码
            size: pageSize.value, // 每页条目数
          },
        });

        // // 提取 data 域
        parkingData.value = response.data.data;
        total.value = response.data.total; // 更新总条目数
        console.log(`total.value = ${total.value}`);
        // 输出转换后的数据
        console.log("转换后的停车数据：");
        console.log(parkingData);

        // 访问特定数据
        // 遍历 parkingData 数组
        parkingData.value.forEach((event: CameraEvent) => {
          console.log(event); // 打印整个事件对象
          console.log(
            `Camera ID: ${event.camera_id}, Camera Name: ${event.camera_name}, ` +
              `Occurrence Time: ${event.occurrence_time}, Event ID: ${event.event_id}, ` +
              `Image Path: ${event.img_path}, License Plate: ${
                event.license_plate ?? "No Plate"
              }, ` +
              `Parking: ${event.parking}`
          );
          event.occurrence_time = formatDate(event.occurrence_time);
        });
      } catch (error) {
        console.error("获取停车数据时发生错误:", error);
      }
    }; // 确保这里关闭了 fetchParkingData 方法

    // 当组件挂载时调用 fetchParkingData
    // onMounted(fetchParkingData);

    // 显示模态框的方法
    const showModal = (imgSrc: string) => {
      currentImageSrc.value = imgSrc;
      if (imgSrc) {
        isModalVisible.value = true;
      }
    };

    const forceRefresh = async () => {
      console.log("立即刷新");
      if (
        selectedCamera.value &&
        selectedCamera.value !==
          t("ui.parkingManagement.pleaseSelectParkingLot")
      ) {
        // 只有当 selectedCamera.value 不是 null 时才调用 fetchParkingData
        await fetchParkingData(selectedCamera.value);
      } else {
        console.log("No camera selected."); // 处理未选择相机的情况
      }
    };
    const testButton = async () => {
      try {
        // const response = await axios.get("/mock/parkingList");
        // 请求数据的 URL
        const response = await axios.get("http://172.30.45.98:8080/events", {
          params: {
            parking: "王庄",
          },
        });
      } catch (error) {
        console.error("获取停车数据时发生错误:", error);
      }
    };

    // 关闭模态框的方法
    const handleCancel = () => {
      isModalVisible.value = false;
    };

    const isAutoRefreshEnabled = ref<boolean>(false);
    let intervalId: number | null = null;
    // 监视 isAutoRefreshEnabled 的变化
    watch(isAutoRefreshEnabled, (newValue) => {
      if (newValue) {
        // 启动定时器
        intervalId = setInterval(async () => {
          console.log("自动刷新");
          if (
            selectedCamera.value &&
            selectedCamera.value !==
              t("ui.parkingManagement.pleaseSelectParkingLot")
          ) {
            // 只有当 selectedCamera.value 不是 null 时才调用 fetchParkingData
            await fetchParkingData(selectedCamera.value);
          } else {
            console.log("No camera selected."); // 处理未选择相机的情况
          }
        }, 2000);
      } else {
        // 清除定时器
        if (intervalId) {
          clearInterval(intervalId);
          intervalId = null;
        }
      }
    });

    // 组件卸载时清除定时器
    const stopPolling = () => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    };

    // 在组件卸载时调用清理函数
    onBeforeUnmount(stopPolling);

    return {
      cameras,
      selectedCamera,
      handleSelect,
      parkingData,
      isModalVisible,
      currentImageSrc,
      showModal,
      handleCancel,
      isAutoRefreshEnabled,
      forceRefresh,
      testButton,
      getImageUrl,
      paginationConfig,
      // renderImage,
    };
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.parking-content {
  width: 100%; // 确保父容器的宽度是100%
  padding: 16px; // 可以根据需要调整内边距
  box-sizing: border-box; // 确保内边距和边框不影响总体宽度
}

.camera-selection {
  display: flex;
  /* 使用flexbox使下拉菜单和选中摄像头在一行上 */
  // align-items: flex-start; /* 垂直居中对齐 */
  // justify-content: space-between;
  margin-bottom: 20px;
  /* 下拉菜单和视频播放器之间的间隔 */
  height: 20px;
  /* 设置高度为20px */
  align-items: center;
  /* 垂直居中对齐 */
  gap: 20px;
  /* 设置元素之间的间隔 */
}

.modal-image {
  max-width: 90%;
  /* 最大宽度为页面的99% */
  max-height: 90%;
  /* 最大高度为页面的90% */
  width: 85%;
}

.modal-image-container {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  width: 100%;
  height: 100%;
}

.modal-image {
  max-width: 100%;
  max-height: 100%;
}

.image {
  cursor: pointer;
  /* 鼠标悬停时显示为手型 */
}

.small-image {
  max-width: 150px;
  /* 设置最大宽度为 150 像素，根据需求调整 */
  max-height: 150px;
  /* 设置最大高度为 150 像素，根据需求调整 */
  width: auto;
  /* 保持宽度自适应 */
  height: auto;
  /* 保持高度自适应 */
  object-fit: cover;
  /* 确保图片不会变形，可以裁剪 */
}

h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

.ant-dropdown {
  z-index: 2000;
  background-color: var(--bg-color);
  /* 提高 z-index 确保下拉菜单在前面 */
}
// .ant-dropdown .ant-dropdown-menu .ant-dropdown-menu-item:hover,
// .ant-dropdown-menu-submenu .ant-dropdown-menu .ant-dropdown-menu-item:hover,
// .ant-dropdown-menu-submenu .ant-dropdown-menu .ant-dropdown-menu-submenu-title-active {
//   background-color: var(--bg-color);
// }
// a {
//   color: #42b983;
// }
</style>

<style>
.custom-table .ant-table {
  /* background-color: #003366;
  color: #ffffff;
  border: 1px solid #0056d2; */
  /* 输入框边框颜色 */

  /* .ant-table-thead > tr > th { */
  /* background-color: #003366;
    color: #ffffff; */
  /* } */

  /* .ant-table-tbody > tr > td { */
  /* color: #ffffff;
    background-color: #003366; */
  /* transition: background-color 0.3s; */
  /* } */

  /* .ant-table-tbody > tr:hover > td {
    background-color: #004080;
  } */

  .ant-empty-normal {
    margin-block: 32px;
    /* color: #cccccc; */
  }
}

/* .custom-table .ant-pagination {
  color: #ffffff;

  .ant-pagination-item-link {
    color: #0056d2;
  }
} */

/* .custom-table .ant-pagination .ant-pagination-item a {
  color: #0056d2;
} */
</style>
